package com.yhm.net.BIO服务端对客户端连接交由单独的线程在线程池中执行用以支撑高连接量但是处理速度比较慢;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BIOServer2 {
  public static void main(String[] args) {
    ExecutorService executorService = Executors.newCachedThreadPool();
    int num = 0 ;
    ServerSocket serverSocket = null;
    try {
      serverSocket = new ServerSocket(8080);
    } catch (IOException e) {
      e.printStackTrace();
    }
    while(true) {

      try {

        Socket socket = serverSocket.accept();
        System.out.println("接收到客户端请求的连接：remoteSocketAddress="+ socket.getRemoteSocketAddress()+" port="+socket.getPort());
        executorService.execute(new Runnable() {//线程个数受到操作系统的限制
          @Override
          public void run() {
            InputStream inputStream = null;
            try {
              inputStream = socket.getInputStream();
              BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
              String str = null;
              while ((str = bufferedReader.readLine()) != null) {
                System.out.println("服务端线程池"+Thread.currentThread().getName()+"接收客户端连接发送过来的数据：" + str);
              }
              bufferedReader.close();
              socket.close();
            } catch (IOException e) {
              e.printStackTrace();
            }

          }
        });
      } catch (IOException e) {
        e.printStackTrace();
      }
    }


  }
}
